package org.nuonuo.sdk.servlet;

import org.nuonuo.sdk.jackson.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Version 1.0
 * @Author az
 * @Date 2024-04-12 09:58:31
 * @ClassName Servlets
 * @Description
 */
public class Servlets {

    private final static Logger log = LoggerFactory.getLogger(Servlets.class);
    private final static String JSON_CONTENT_TYPE="application/json";
    public static HttpServletResponse getResponse(){
        ServletRequestAttributes requestAttributes=getServletRequest();
        if(requestAttributes==null)return null;
        return requestAttributes.getResponse();
    }

    public static void write(Object body) {
        write(getResponse(), body, JSON_CONTENT_TYPE);
    }

    public static void write(Object body, String contentType) {
        write(getResponse(), body, contentType);
    }

    public static void write(HttpServletResponse response, Object body, String contentType) {
        try {
            response.setContentType(contentType == null ? JSON_CONTENT_TYPE : contentType);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(body instanceof String ? body : JsonMapper.toJson(body));
        } catch (IOException e) {
            log.error("HttpServletResponse writer print error", e);
        }
    }

    private static ServletRequestAttributes getServletRequest(){
        try{
            return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes());
        }catch(Exception e) {
            log.error("Cant not get ServletRequestAttributes", e);
            return null;
        }
    }
}
